package com.work.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Given a string, find the length of the longest substring without repeating characters.
 * Created by suk on 2018/10/24.
 */
public class SubString_02_pass_N3 {
    public static void main(String[] args) {
        SubString_02_pass_N3 o = new SubString_02_pass_N3();
        String s = "nfdmpi";
        System.out.println(o.lengthOfLongestSubstring(s));
    }
    public int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1)
            return s.length();
        int ans = 0;
        Map<Character, Integer> hashMap = new HashMap();
        // ans 记录最长子序列；i 用来记录游标；j 用来记录重复字符的位置
        for (int i = 0, j = 0; i < s.length(); i++) {
            if (hashMap.containsKey(s.charAt(i))) {
                j = Math.max(j, hashMap.get(s.charAt(i)));
            }
            ans = Math.max(ans, i - j + 1);
            hashMap.put(s.charAt(i), i + 1);
        }
        return ans;
    }
}
